package cn.hn.java.summer.db.paging;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;

import cn.hn.java.summer.db.builder.FormatResult;
import cn.hn.java.summer.db.builder.SqlBuilder;

/**
 * sybase分页转换
 * @author sjg
 * @version 1.0.1 2013-10-26
 *
 */
public class SybasePagingConverter implements IPagingConverter {
	static final Log logger = LogFactory.getLog(SybasePagingConverter.class);

	/**
	 * 分页方法
	 */
	public <T> List<T> paging(JdbcTemplate jdbcTemplate, final String sql, final int pageSize, final int page,RowMapper<T> rowMapper,Object...args) {
		
		return 
		jdbcTemplate.query(new PreparedStatementCreator() {
			
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				//包一层存储过程调用
				PreparedStatement ps=con.prepareCall("{call GetDataByPage(?,?,?)}");
				logger.debug("{call GetDataByPage(?,?,?)}");
				logger.debug(sql);
				//设置分页
				ps.setString(1, sql);
				ps.setInt(2, pageSize);
				ps.setInt(3, page);
				return ps;
			}
		}, rowMapper);
	}

	/**
	 * 取sql
	 */
	public FormatResult formatSql(String sql,Object...args) {	
		//格式化成可执行sql
		FormatResult rst=SqlBuilder.format(sql,true,args);
		return rst;
	}

}
